import knex, { Knex } from "knex";
import fs from "fs";
import path from "path";
let dbInstance: Knex;
// 主进程和渲染进程都各自拥有独立的DB实例  每个进程都相互独立
// SQLite 不支持并发写入数据，两个或两个以上的写入操作同时执行时，只有一个写操作可以成功执行，其他写操作会失败。并发读取数据没有问题。
if (!dbInstance) {
  let dbPath;
  if (location.href.startsWith("https")) {
    dbPath = path.join(process.execPath, "../../../../src/common/db.db");
  } else {
    dbPath = process.env.APPDATA || (process.platform == "darwin" ? process.env.HOME + "/Library/Preferences" : process.env.HOME + "/.local/share");
    dbPath = path.join(dbPath, "electron-lbxin/db.db");
    console.log(dbPath,'dbPath ======== ')
    let dbIsExist = fs.existsSync(dbPath);
    console.log("copy", dbIsExist, dbPath);
    if (!dbIsExist) {
      let resourceDbPath = path.join(process.execPath, "../resources/db.db");
      fs.copyFileSync(resourceDbPath, dbPath);
      console.log("copy");
    }
  }
  console.log(dbPath,'dbPath ======== ')
  dbInstance = knex({
    client: "better-sqlite3",
    connection: { filename: dbPath },
    useNullAsDefault: true,
  });
}
export let db = dbInstance;
